// vuex管理token

import { login, getPerms, getUserInfo, editUser } from '@/api/user'
import { Message } from 'element-ui'
const state = {
  // 保存数据
  token: localStorage.getItem('fc-token') || '',
  userInfo: JSON.parse(localStorage.getItem('user')) || {},
  permsList: JSON.parse(localStorage.getItem('fc-perms')) || []

}

const mutations = {
  // 登录 获取用户信息和token
  setToken(state, payload) {
    const { token } = payload
    state.token = token
    // 把传过来的参数(是对象格式)转换成json格式存到本地
    localStorage.setItem('fc-token', state.token)
  },
  // 获取权限
  setPerms(state, data) {
    state.permsList = data
    console.log('data', data)
    localStorage.setItem('fc-perms', JSON.stringify(data))
  },
  // 获取用户信息
  setUserInfo(state, payload) {
    console.log(30, payload)
    state.userInfo = payload
    localStorage.setItem('user', JSON.stringify(state.userInfo))
  }

}

const actions = {
  // 登录 发送请求
  async login(store, payload) {
    console.log(45, payload, '登录事件')
    const response = await login(payload)
    console.log(45, response)
    try {
      // 判断成功之后跳转
      if (response.status === 200) {
      // 用store保存 token
      // 保存token 需要用'Bearer '拼接
        const res = {
          token: 'Bearer ' + response.data.jwt,
          user: response.data.user
        }
        console.log(50, res)
        store.commit('setToken', res)
        localStorage.setItem('loginTime', Date.now())
      }
    } catch (error) {
      console.dir(68, error)
      return
      // console.log(error)
    }
  },
  // 编辑头像
  async editInfo(store, payload) {
    console.log(70, payload.image[0].url)
    const res = await editUser(payload)
    // 判断返回值是不是ok
    if (res.status === 200) {
      Message({
        type: 'success',
        message: '头像修改成功'
      })
    }
    store.commit('setUserInfo', res.data)
  },

  // 获取权限列表
  async getPerms(store) {
    const res = await getPerms()
    console.log('权限列表', res)
    store.commit('setPerms', res.data.menus)
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    console.log('用户信息', res)
    store.commit('setUserInfo', res.data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
